#!/bin/bash
# Produces a list of changed files between two commits (works for merges and
# regular commits).
# Used in conjunction with the monorepo-diff-buildkite-plugin to determine
# which pipelines to upload/trigger based on the files changed.

[ $# -lt 1 ] && { echo "argument is missing."; exit 1; }

COMMIT=$1

if [ -n $BUILDKITE_PULL_REQUEST_BASE_BRANCH ]; then
  HEAD_BRANCH="origin/$BUILDKITE_PULL_REQUEST_BASE_BRANCH"
  MERGE_BASE=$(git merge-base "$HEAD_BRANCH" "$COMMIT")
  echo "Checking against a base branch: $BUILDKITE_PULL_REQUEST_BASE_BRANCH with merge base at $MERGE_BASE"
  git diff --raw "$COMMIT".."$MERGE_BASE" | awk '{print $6; if($7) {print $7}}'
else
  echo "Checking against the head of the current branch"
  git diff --raw HEAD~1 | awk '{print $6; if($7) {print $7}}'
fi
